<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Token;
use app\common\library\Upload;
use app\common\model\Canal;
use app\common\model\Dynatown;
use app\common\model\Ibec;
use app\common\model\Staff;
use app\common\model\StaffUpdate;
use app\common\model\Type;
use think\Validate;

/**
 * 登录接口
 */
class Login extends Api
{
    protected $noNeedLogin = ['staffLogin','canalLogin','wxlogin'];
    protected $noNeedRight = ['*'];

    /**
     * 获取用户openid
     * */
    public function wxlogin(){
        $validate = new \think\Validate([
            ['code', 'require', 'code不能为空'],
            ['avatar', 'require', '头像不能为空'],
            ['nickname', 'require', '昵称不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $type=!$this->request->param("type")?0:$this->request->param("type");
        if($type!=0 && $type!=1){
            $type=0;
        }
        $code = $this->request->param("code");
        $result = getOpenid($code,$type);
       /* $result["openid"]="ot6sO5f6GrgT2qaqtOZXHiX6nnSo";
        $result["session_key"]="pu81Rs/sx2LTHFUsn09ATg==";*/

        //自然流量
        /*$result["openid"]="ouGm25dphT_nQxR2DfagmCoV7TLA";
        $result["session_key"]="RUalAe+aSL7Axm0Q4gv9Ug==";*/
        if (!isset($result['openid'])) {
            $this->error('请求错误', $result);
        }
        $data = [
            "nickname" => $this->request->param("nickname"),
            "avatar" => $this->request->param("avatar"),
            "openid" => $result['openid'],
            "session_key" => $result['session_key'],
        ];
        $ret = $this->auth->login('','',$type,$data);
        if ($ret) {
            $user=$this->auth->getUserinfo();
            $token=$user["token"];
            if($type==1){
                $user=Staff::with(["ibec"=>function($query){
                    $query->withField('id,name');
                }])->where(["staff.id"=>$this->auth->id])->find();
            }else{
                $user=\app\common\model\Connection::field("id,nickname,avatar,phone mobile")->where(["id"=>$user["user_id"]])->find();
            }
            $user["type"]=$type;
            $user["token"]=$token;
            $this->success("登录成功", $user);
        } else {
            $this->error($this->auth->getError());
        }
        $this->success("成功",$user);
    }
    /**
     * 获取用户手机号码
     * */
    public function getWxPhone()
    {
        $type=!$this->request->param("type")?0:$this->request->param("type");
        if($type!=0 && $type!=1){
            $type=0;
        }
        $tmp = getAccessToken($type);
        $token = $tmp["access_token"];
        $data['code'] = input('code');
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        $info = \fast\Http::post($url,json_encode($data),'json');
        // 一定要注意转json，否则汇报47001错误
        $tmpinfo = json_decode($info,true);
        if ($tmpinfo["errcode"]  == 0) {
            $update=["mobile"=>$tmpinfo["phone_info"]["purePhoneNumber"]];
            if(empty($type)){
                $update=[];
                $update["phone"]=$tmpinfo["phone_info"]["purePhoneNumber"];
                $update["phone_see"]=$tmpinfo["phone_info"]["purePhoneNumber"];
                $ret=\app\common\model\Connection::where(["id"=>$this->auth->id])->update($update);
            }else{
                $ret=Staff::where(["id"=>$this->auth->id])->update($update);
            }
        } else {
            $this->error($tmpinfo["errcode"] );
        }
        $this->success("成功",["mobile"=>$tmpinfo["phone_info"]["purePhoneNumber"]]);
    }
    /**
     * 经纪公司完善资料
     * */
    public function perfect(){
        $validate = new \think\Validate([
            ['name', 'require', '姓名不能为空'],
            ['ibec_id', 'require', '所属经纪公司不能为空'],
            ['type_data', 'require', '身份不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param= $this->request->param();
        if($param["type_data"]!=0 && $param["type_data"]!=1){
            $this->error('身份选择错误');
        }
        $param["status"]='1';
        if($param["type_data"]==1){
            $param["status"]='0';
        }
        $staff=Staff::get($this->auth->id);
        $staff->allowField(true)->save($param);
        $staff=Staff::with(["ibec"=>function($query){
            $query->withField('id,name');
        }])->where(["staff.id"=>$this->auth->id])->find();
        $this->success("成功",$staff);
    }
    /**
     * 自然流量填写姓名
     * */
    public function fillName(){
        $validate = new \think\Validate([
            ['moniker', 'require', '姓名不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $user=\app\common\model\Connection::get($this->auth->id);
        $param= $this->request->param();
        $user->save([
            /*"surname"=>$param["surname"],
            "name"=>$param["name"],*/
            "moniker"=>$param["moniker"],
        ]);
        $this->success("成功",$user);
    }
    /**
     * 获取自然用户资料
     * */
    public function getUser(){
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token=Token::get($token);
        if($token["type"]!=0) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        $user=\app\common\model\Connection::field("id,nickname,phone mobile,avatar,openid,code,moniker,strike_data")
            ->where(["id"=>$this->auth->id])
            ->find();
        $this->success("成功",$user);
    }
    /**
     * 获取经纪人资料
     * */
    public function getStaff(){
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token=Token::get($token);
        if($token["type"]!=1) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        $user=Staff::field("id,nickname,mobile,avatar,openid,name,status,remark,type_data")
            ->with(["ibec"=>function($query){
            $query->withField('id,name');
        }])->where(["staff.id"=>$this->auth->id])->find();
        $user["platformMobile"]=\think\Config::get('site.platformMobile');
        $this->success("成功",$user);
    }
    /**
     * 获取渠道驻场资料
     * */
    public function getdDynatown(){
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token=Token::get($token);
        if($token["type"]!=3) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        $user=Dynatown::field("id,nickname,avatar,openid,name")->where(["id"=>$this->auth->id])->find();
        $this->success("成功",$user);
    }
    /**
     * 获取置业顾问资料
     * */
    public function getCanal(){
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token=Token::get($token);
        if($token["type"]!=2) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        /*判断当前账号身份 end*/
        $user=Canal::field("id,nickname,mobile,avatar,openid,name")->where(["id"=>$this->auth->id])->find();
        $this->success("成功",$user);
    }

    /**
     * staff经纪公司登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function staffLogin()
    {
        $validate = new \think\Validate([
            ['code', 'require', 'code不能为空'],
            ['avatar', 'require', '头像不能为空'],
            ['nickname', 'require', '昵称不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $user=$this->auth->getUser();
        $user=\app\common\model\User::get($user["id"]);
        $code = $this->request->param("code");
        $result = getOpenid($code);
        if (!isset($result['openid'])) {
            $this->error('请求错误', $result);
        }
        $data = [
            "nickname" => $this->request->param("nickname"),
            "avatar" => $this->request->param("avatar"),
            "openid" => $result['openid'],
            "session_key" => $result['session_key'],
        ];
        $ret = $this->auth->login('','',1,$data);
        if ($ret) {
            $user=$this->auth->getUserinfo();
            $userinfo=[
                "id"=>$user["id"],
                "nickname"=>$user["nickname"],
                "avatar"=>$user["avatar"],
                "token"=>$user["token"],
            ];
            $this->success(__('登录成功'), $userinfo);
        } else {
            $this->error($this->auth->getError());
        }
        $this->success("成功",$user);
    }
    /**
     * staff置业顾问登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function canalLogin()
    {
        $data=[
            ['account', 'require', '账户不能为空'],
            ['password', 'require', '密码不能为空'],
            ['type', 'require', '类型不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $type = !$this->request->post('type')?2:$this->request->post('type');
        if($type!=2 && $type!=3) $type=2;
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password,$type);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $nickname 昵称
     * @param string $mobile      手机号码
     * @param string ibec_id      经纪公司
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        //$username = $this->request->post('username');
        /*if ($nickname) {
            if(empty($type)){
                $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            }
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }*/
        $data=[];
        $staff=[];
        if($this->request->post('nickname')){
            $nickname = $this->request->post('nickname');
            $data["nickname"]= $nickname;
        }
        if($this->request->post('avatar')){
            $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
            $data["avatar"]= $avatar;
        }
        if($this->request->post('mobile')){
            $mobile = $this->request->post('mobile');
            if($this->request->post('mobile') && !Validate::regex($mobile, "^1\d{10}$")){
                $this->error("手机号码格式错误");
            }
            $data["mobile"] = $mobile;
            $staff["before_mobile"]=$user["mobile"];
            $staff["after_mobile"]=$mobile;
            $content="将手机号".$user["mobile"]."修改为".$mobile;
        }
        if($this->request->post('ibec_id')){
            $ibec_id = $this->request->post('ibec_id');
            $before_ibec=Ibec::field("name")->find(["id"=>$user["ibec_id"]]);
            $after_ibec=Ibec::field("name")->find(["id"=>$ibec_id]);
            $type='0';
            if(empty($before_ibec)) $before_ibec["name"]="无";
            if(!empty($staff)){
                $type='1';
                $content.="，将经纪公司“".$before_ibec["name"]."”修改为“".$after_ibec["name"]."”";
            }else{
                $content="将经纪公司“".$before_ibec["name"]."”修改为“".$after_ibec["name"]."”";
            }
            $staff_data=[
                "type_data"=>$type,
                "before_ibec_id"=>$user["ibec_id"],
                "before_ibec"=>$before_ibec["name"],
                "after_ibec_id"=>$ibec_id,
                "after_ibec"=>$after_ibec["name"],
                "staff_id"=>$this->auth->id,
                "content"=>$content,
            ];
            $data["ibec_id"]=$ibec_id;
            $staff=array_merge($staff,$staff_data);
            StaffUpdate::create($staff);
        }
        if(!empty($data)){
            $user->save($data);
            $this->success("成功");
        }else{
            $this->error("请填写修改项");
        }
    }

    /**
     * 信息修改记录
     * */
    public function updateSee(){
        $list=StaffUpdate::field("id,before_mobile,after_mobile,before_ibec,after_ibec,type_data,content,from_unixtime(createtime, '%Y') year,from_unixtime(createtime, '%m.%d') date")
            ->where(["staff_id"=>$this->auth->id])->order("createtime","desc")->select();
        $this->success("获取成功",$list);
    }

    /**
     * 获取当前经纪公司下的所有经纪人列表
     * */
    public function staffList(){
        $user=$this->auth->getUser();
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token=Token::get($token);
        if($token["type"]!=1) $this->error("身份错误");//1 经纪人 2置业顾问 3渠道驻场
        if($user["type_data"]!=1) $this->error("身份错误");//身份:0=经纪人,1=经纪人公司驻场
        /*判断当前账号身份 end*/
        $list=Staff::field("id,name,mobile")
            ->where(["ibec_id"=>$user["ibec_id"],"type_data"=>'0'])->order("createtime","desc")->select();
        $this->success("获取成功",$list);

    }

}
